package cn.hgy.types.tree;

import lombok.Data;

// 策略路由器
@Data
public abstract class AbstractStrategyRouter<T, D, R> implements StrategyMapper<T, D, R>, StrategyHandler<T, D, R> {

    protected StrategyHandler<T, D, R> defaultStrategyHandler = StrategyHandler.DEFAULT;

    /**
     * 核心路由方法，负责完成 “策略选择→策略执行” 的标准化流程
     * @param requestParameter
     * @param dynamicContext
     * @return
     * @throws Exception
     */
    public R router(T requestParameter, D dynamicContext) throws Exception {
        // 1. 根据入参和上下文选择策略处理器
        StrategyHandler<T, D, R> strategyHandler = get(requestParameter, dynamicContext);

        // 2. 执行策略：存在匹配策略则执行，否则使用默认策略
        if(null != strategyHandler) return strategyHandler.apply(requestParameter, dynamicContext);
        return defaultStrategyHandler.apply(requestParameter, dynamicContext);
    }
}
